package com.ledi.guns.modular.ledipay.service.impl;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import sun.misc.BASE64Decoder;

import com.ledi.guns.common.exception.AppCheckException;
import com.ledi.guns.common.persistence.dao.SchoolQrMapper;
import com.ledi.guns.common.persistence.dao.UserMapper;
import com.ledi.guns.common.persistence.model.SchoolPayQr;
import com.ledi.guns.common.persistence.model.User;
import com.ledi.guns.core.base.tips.ErrorTip;
import com.ledi.guns.core.base.tips.SuccessTip;
import com.ledi.guns.core.base.tips.Tip;
import com.ledi.guns.core.shiro.ShiroKit;
import com.ledi.guns.core.shiro.ShiroUser;
import com.ledi.guns.core.util.FileUtil;
import com.ledi.guns.modular.ledipay.controller.req.school.SchoolQrReq;
import com.ledi.guns.modular.ledipay.service.SchoolQrService;

@Service
public class SchoolQrServiceImpl implements SchoolQrService {

	@Autowired
	private UserMapper userMapper;

	@Autowired
	private SchoolQrMapper schoolQrMapper;

	protected final static Logger log = LoggerFactory.getLogger(SchoolQrServiceImpl.class);

	/**
	 * 图片上传的格式
	 */
	@Value("${app.access.img.type}")
	private String[] imgTypes;

	@Value("${cos.appid}")
	private String cosAppid;

	@Value("${cos.secret.id}")
	private String cosSecretId;

	@Value("${cos.secret.key}")
	private String cosSecretKey;

	@Value("${cos.region}")
	private String cosRegion;

	@Value("${cos.bucket.name}")
	private String cosBucketName;

	@Value("${cos.file.root.url}")
	private String cosFileRootUrl;

	@Value("${import.file.address}")
	private String importFileAddress;

	@Override
	@Transactional
	public Tip uploadQr(SchoolQrReq schoolQrReq) {

		ShiroUser currentUser = ShiroKit.getUser();
		User oneUsers = userMapper.selectById(currentUser.getId());
		log.info("uploadQr查询当前用户信息{}", oneUsers);
		if (1 != oneUsers.getStatus()) {
			throw new AppCheckException("school.user.notActive.code", "school.user.notActive.message");
		}
		schoolQrMapper.deleteSchoolQr(oneUsers.getSchoolId());
		// 上传文件
		String picUrl = "";
		try {
			picUrl = convertBase64ToFile(schoolQrReq);
		} catch (IOException e) {
			log.info("学校ID{}上传当面付二维码异常,{}", oneUsers.getSchoolId(), e.getMessage());
			throw new AppCheckException("school.uploadQrCode.code", "school.uploadQrCode.message");
		}
		SchoolPayQr record = new SchoolPayQr();
		record.setShcoolId(oneUsers.getSchoolId());
		record.setCreateUser(oneUsers.getId().toString());
		record.setCreateTime(new Date());
		record.setType(schoolQrReq.getType());
		record.setPicUrl(picUrl);
		record.setImgUrl(schoolQrReq.getImgUrl());
		int result = schoolQrMapper.insert(record);
		if (result > 0) {
			String url = cosFileRootUrl + picUrl;
			Map<String, String> map = new HashMap<String, String>(1);
			map.put("picUrl", url);
			return SuccessTip.buildSuccess(map);
		}
		return ErrorTip.buildFailure(60001, "上传二维码失败");
	}

	@Override
	public Tip queryQr() {

		ShiroUser currentUser = ShiroKit.getUser();
		User oneUsers = userMapper.selectById(currentUser.getId());
		log.info("queryQr查询当前用户信息{}", oneUsers);
		if (1 != oneUsers.getStatus()) {
			throw new AppCheckException("school.user.notActive.code", "school.user.notActive.message");
		}
		SchoolQrReq result = schoolQrMapper.querySchoolQr(oneUsers.getSchoolId());
		log.info("查询乐校收二维码信息{}", result);
		if (null != result) {
			String url = cosFileRootUrl + result.getPicInfo();
			log.info("》》》》学校ID{}返回二维码地址{}", oneUsers.getSchoolId(), url);
			Map<String, String> map = new HashMap<String, String>(1);
			map.put("picUrl", url);
			map.put("imgUrl", result.getImgUrl());
			map.put("type", result.getType());
			return SuccessTip.buildSuccess(map);
		}
		return ErrorTip.buildFailure(60002, "查询二维码失败");
	}

	/**
	 * 文件base64
	 * 
	 * @param pic
	 * @return
	 * @throws IOException
	 */
	public String convertBase64ToFile(SchoolQrReq pic) throws IOException {

		byte[] bytes = new BASE64Decoder().decodeBuffer(pic.getPicInfo());
		for (int i = 0; i < bytes.length; ++i) {
			if (bytes[i] < 0) {// 调整异常数据
				bytes[i] += 256;
			}
		}
		InputStream sbs = new ByteArrayInputStream(bytes);
		String imgUrl = pic.getImgUrl();
		FileUtil.uploadFile(sbs, imgUrl.substring(imgUrl.indexOf(".") + 1, imgUrl.length()), cosSecretId, cosSecretKey, cosBucketName, cosAppid);
		return null;
	}

}
